package com.sinai.mshab.client.widgets;

import java.util.HashMap;
import java.util.Iterator;

import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * This creates a collection of radio buttons given some choices
 * 
 * This class also provides an easy way to get to individual radios based on
 * their name.
 * 
 * @author serge
 * 
 */
public class RadioCollection extends FocusPanel {

	private HashMap<String, RadioButton> choiceToRadio = new HashMap<String, RadioButton>();

	/**
	 * Creates a new collection of radio buttons given choices and a name.
	 * 
	 * @param name
	 *            the name of the collection
	 * @param choices
	 *            list of choices offered in the collection.
	 * @param vertical
	 *            should this list be aligned horizontally or vertically
	 */
	public RadioCollection(String name, String[] choices, boolean vertical) {

		// configure the panel
		setStyleName("mshab-RadioCollection");

		// figure out what type of panel to use.
		Panel p;
		if (vertical) {
			p = new VerticalPanel();
		} else {
			p = new HorizontalPanel();
		}

		// make a new radio button for each choice we are given
		for (int i = 0; i < choices.length; i++) {
			String choice = choices[i];
			RadioButton radio = new RadioButton(name, choice);
			choiceToRadio.put(choice, radio);
			p.add(radio);
		}
		add(p);
	}

	/**
	 * Returns a reference of the radio button with the provided choice
	 * 
	 * @param choice
	 *            the choice of the button to be returned
	 * @return the radio button with specified choice.
	 */
	public RadioButton getRadio(String choice) {
		return choiceToRadio.get(choice);
	}

	/**
	 * Returns true if at least one radio in this group is checked.
	 * 
	 * @return true if at least one radio in this group is checked.
	 */
	public boolean isChecked() {
		Iterator it = choiceToRadio.keySet().iterator();
		boolean set = false;
		while (it.hasNext()) {
			set |= getRadio((String) it.next()).isChecked();
		}
		return set;
	}

	/**
	 * Return the value of the selected radio button.
	 * 
	 * @return
	 */
	public String getValue() {
		Iterator it = choiceToRadio.keySet().iterator();
		while (it.hasNext()) {
			String choice = (String) it.next();
			RadioButton rad = getRadio(choice);
			if (rad.isChecked()) {
				return choice;
			}
		}
		return null;
	}

	/**
	 * Sets the value to the collection
	 * 
	 * @param string
	 *            the value to set.
	 */
	public void setValue(String string) {
		Iterator it = choiceToRadio.keySet().iterator();
		while (it.hasNext()) {
			String value = (String) it.next();
			
			if (value.equals(string)) {
				RadioButton button = choiceToRadio.get(value);
				button.setChecked(true);
			}
		}
	}
}
